package com.myGisChannel.controller;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.myGis.entities.Project;
import com.myGis.entities.User;
import com.myGis.services.IMyGisServices;
import com.myGis.services.MyGisServer;
import com.myGisChannel.view.UserView;

/**
 * 
 * @author Diego Gonzalez - jose Vigna
 * Este controlador es invocado cuando el usuario se loguea, luedo del proceso correspondiente, redirecciona a <code>projectDetails.jsp</code>
 * Consideraciones: 
 * --> Si el usario no exite arroja un <code>AuthenticationException</code>, esto se refleja con un mensaje en la pantalla de loguin.
 *  
 */

public class ProjectDetailsController extends AbstractController {

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws AuthenticationException{
		
		SecurityContextImpl ssi = (SecurityContextImpl) request.getSession(true).getAttribute("SPRING_SECURITY_CONTEXT");
		UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) ssi.getAuthentication();
		
		List<GrantedAuthority> authorities = (List<GrantedAuthority>) authentication.getAuthorities();
		
		IMyGisServices mgs = MyGisServer.getInstance();
		User user = mgs.loguinUser(authentication.getName(), "");
		if(user!=null){
			request.getSession(true).setAttribute("user", user);
			UserView userView = new UserView(user);
			//Copia los roles que tiene asociado el usuario a UserView.
			for (Iterator iterator = authorities.iterator(); iterator.hasNext();) {
				GrantedAuthorityImpl gai = (GrantedAuthorityImpl) iterator.next();
				userView.addRol(gai.getAuthority());
			}
		}

		
		
		ModelAndView model = null;	
		
		model = new ModelAndView("projectDetails");
		List<Project> projects =  user.getProjects();
		model.addObject("projects", projects);
		return model;
	}
}